<?php

//腾讯云 COS 图片上传
function QclouduUpload($key, $filepath){
    $cosClient = new \Qcloud\Cos\Client([
            'region'    =>  Config('app')['region'],
            'credentials'   =>  [
                'secretId'      => Config('app')['secretId'],
                'secretKey'     => Config('app')['secretKey'],
            ]
        ]
    );
    ### 上传文件流
    try {
        $result = $cosClient->Upload(
            $bucket = Config('app')['bucket'],
            $key = $key,
            $body = fopen($filepath, 'rb')
        );
        return Config('app')['cos_url'] . $key;
    } catch (\Exception $e) {
        echo "$e\n";die;
    }
}

//处理ueditor里面的图片(链接换成腾讯cos源)
function parseUeditorImage($content){
    $img_pattern = '/<img(.*)src="(.*)"(.*)>/isU';
    preg_match_all($img_pattern,$content,$img_list);
    if(is_array($img_list[2])){
        foreach ($img_list[2] as $img_url) {
            if(strpos($img_url,Config('app')['cos_url'])===false){
                $key = md5(uniqid(md5(microtime(true)),true));
                if(preg_match("/^(http:\/\/|https:\/\/|\/\/).*$/", $img_url)){
                    //网络图片
                    if(getImg($img_url, public_path() . '/picture/' . $key)){
                        $img_real_path = public_path() . '/picture/' . $key;
                    }
                }else{
                    //本地图片
                    $img_real_path = public_path() . $img_url;
                }
                $content = str_replace(
                    $img_url,
                    QclouduUpload($key, $img_real_path),
                    $content
                );
                unlink($img_real_path);
            }
        }
    }
    return $content;
}

//下载网络图片到本地
function getImg($url = "", $filename = ""){
    $hander = curl_init();
    $fp = fopen($filename,'wb');
    curl_setopt($hander,CURLOPT_URL,$url);
    curl_setopt($hander,CURLOPT_FILE,$fp);
    curl_setopt($hander,CURLOPT_HEADER,0);
    curl_setopt($hander,CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($hander,CURLOPT_TIMEOUT,60);
    curl_setopt($hander, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
    curl_setopt($hander, CURLOPT_SSL_VERIFYHOST, false); // 检查证书中是否设置域名（为0也可以，就是连域名存在与否都不验证了）
    curl_exec($hander);
    curl_close($hander);
    fclose($fp);
    return true;
}